package com.su.kddq.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.su.kddq.entity.user.Address;
import com.su.kddq.mapper.user.AddressMapper;
import com.su.kddq.service.user.AddressService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sx
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Override
    public boolean addAddress(Address address) {
        try {
            if (address.getAddressDefault() == 1) {
                Address addressInfo;
                addressInfo = this.getOne(new QueryWrapper<Address>().eq("uid", address.getUid()).eq("address_default", 1));
                if (!StringUtils.isEmpty(addressInfo)) {
                    addressInfo.setAddressDefault(0);
                    this.updateById(addressInfo);
                }
            }
            this.saveOrUpdate(address);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Address> getAddressList() {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        List<Address> addressList = this.list(new QueryWrapper<Address>().eq("uid", name).orderByDesc("address_default"));
        List<Address> addresses = addressList.stream().map(address -> {
            address.setAddressinfo(address.getProvince() + address.getCity() + address.getCounty() + " " + address.getAddressinfo());
            return address;
        }).collect(Collectors.toList());
        return addresses;
    }
}
